import os
import threading
from threading import Timer

# File: RunGitAutoUpdate_forBlog.py
# Author: HowardXue https://howiexue.blog.csdn.net/

BRANCH_NAME_TARGET = "xxxxxxxx"
BRANCH_NAME_DEV = "xxxxxxxx"

SUBMODULE_NAME_1 = "xxxx"
SUBMODULE_NAME_2 = "xxxx"

# check periodic in seconds
RUN_PERIODIC_SECOND = 60*5

def executeGitCmd(cmd):
    try:
        result = os.popen(cmd)
        rstStr = result.read()
        # print(rstStr)
    except:
        print("Error occured when executeGitCmd")

    return rstStr


def switchToBranch(branchName):
    cmd = 'git symbolic-ref --short HEAD'
    # check if already in this branch
    currentBranch = executeGitCmd(cmd)
    if currentBranch == (branchName+"\n"):
        return
    else:
        # switch to branch
        print("switch to branch: " + branchName)
        cmd = 'git checkout ' + branchName
        ret = executeGitCmd(cmd)
        print(ret)




def isRemoteModified_Submodule(smName):
    cmd = 'git rev-parse @:' + smName
    localRev = executeGitCmd(cmd)

    # In SubModule folder check remote rev
    os.chdir(smName)
    switchToBranch(BRANCH_NAME_DEV)

    cmd = 'git remote -v update'
    ret = executeGitCmd(cmd)

    cmd = 'git rev-parse @{u}'
    remoteRev = executeGitCmd(cmd)

    os.chdir("../")

    print(smName + " Local is: " + localRev)
    print(smName + " Remote is: " + remoteRev)

    if localRev == remoteRev:
        return False
    else:
        return True

def pullSubModule(smName):
    os.chdir(smName)
    switchToBranch(BRANCH_NAME_DEV)

    cmd = 'git pull --progress -v --no-rebase "origin" '+ BRANCH_NAME_DEV
    ret = executeGitCmd(cmd)
    print(ret)
    os.chdir("../")



def doPeriodicFunction(count):
    print('>>> Auto checking periodically, run times:')
    count+=1
    print(count)
    autoUpdate()

    global timer
    timer = threading.Timer(RUN_PERIODIC_SECOND, doPeriodicFunction, (count,))
    timer.start()

def checkSubmodule(smName):
    result = isRemoteModified_Submodule(smName)
    if result == True:
        print(">>> remote submodule: " + smName + " changed !, start pull...")
        pullSubModule(smName)
    else:
        print(">>> remote submodule: "+smName+" Not changed...")
    return result

def autoUpdate():
    switchToBranch(BRANCH_NAME_TARGET)

    status_hon = checkSubmodule(SUBMODULE_NAME_1)
    status_fw  = checkSubmodule(SUBMODULE_NAME_2)

    if (status_fw == True) or (status_hon == True):
        print(">>> start push to remote...")

        cmd = 'git commit -a -m "Auto Merge smb or honeycomb change by Tools"'
        ret = executeGitCmd(cmd)
        print(ret)

        cmd = 'git push "origin" ' + BRANCH_NAME_TARGET
        ret = executeGitCmd(cmd)
        print(ret)



def main():
    print('>>> Auto Git Merge Tool start... \n')
    doPeriodicFunction(0)



if __name__ == '__main__':
    main()


